package com.freesky.biz.activity.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.freesky.biz.activity.domain.TSmsCode;
import com.freesky.biz.activity.mapper.SmsCodeMapper;
import com.freesky.biz.activity.service.ISmsCodeService;
import com.freesky.biz.utils.SeqUtil;
import com.freesky.common.config.Constant;
import com.freesky.common.core.redis.RedisCache;
import com.freesky.common.utils.StringUtils;
import com.freesky.framework.web.service.SendAlarmService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class SmsCodeServiceImpl implements ISmsCodeService {

    private static DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
            "LTAI4FgZVdh7xxLwQP4UDmBC", "iNiNGFvFQLOZnLt17l7pbaagdHETgf");

    private static IAcsClient client = new DefaultAcsClient(profile);

    private static final String SYMBOLS = "0123456789"; // 数字


    @Autowired
    private SmsCodeMapper smsCodeMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SendAlarmService sendAlarmService;

    @Override
    public List<TSmsCode> findList(TSmsCode entity) {
        return smsCodeMapper.findList(entity);
    }


    @Override
    public boolean checkValidCode(String mobile, String code) {
        if(StringUtils.isEmpty(code)){
            return false;
        }
        String redisKey = Constant.REDIS_VALID_CODE + mobile;
        String validCodeInfo = (String)redisCache.getCacheObject(redisKey);
        if(StringUtils.isNotEmpty(validCodeInfo)){
            JSONObject jsonObject = JSONObject.parseObject(validCodeInfo);
            String validCode = jsonObject.getString("code");
            if(code.equalsIgnoreCase(validCode)){
                redisCache.deleteObject(redisKey);
                return true;
            }
        }
        return false;
    }

    @Override
    public int sendSmsCode(String mobile, String templateCode, String openId, String origin) {
        String redisKey = Constant.REDIS_VALID_CODE + mobile;

        int retCode = 0;
        String code = (String)redisCache.getCacheObject(redisKey);
        if(StringUtils.isNotEmpty(code)){
            JSONObject jsonObject = JSONObject.parseObject(code);
            long msec = jsonObject.getLongValue("createTime");
            long cursec = System.currentTimeMillis();
            if((cursec - msec) / 1000 < 60){
                redisCache.setCacheObject(redisKey,code,60*2, TimeUnit.SECONDS);
                return retCode;
            }
        }
        code = "";
        for(int i=0;i<4;i++){
            code = code + SYMBOLS.charAt(new Random().nextInt(SYMBOLS.length()));
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("createTime", System.currentTimeMillis());

        //缓存（60秒）
        redisCache.setCacheObject(redisKey,jsonObject.toJSONString(),60*2,TimeUnit.SECONDS);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "融易兑");
        //SMS_206570115
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", jsonObject.toJSONString());

        try {
            CommonResponse response = client.getCommonResponse(request);
            TSmsCode smsSendModel = new TSmsCode();
            smsSendModel.setId(SeqUtil.getSeqId());
            smsSendModel.setMobile(mobile);
            smsSendModel.setCode(code);
            smsSendModel.setOpenId(openId);
            smsSendModel.setTemplateCode(templateCode);
            smsSendModel.setRespData(response.getData());
            smsSendModel.setOrigin(origin);
            smsCodeMapper.addSmsLog(smsSendModel);
        } catch (Exception e) {
            retCode = -1;
            e.printStackTrace();
        }
        return retCode;
    }

    @Override
    public int sendPsbcCardNo(String mobile,
                              String templateCode,
                              String templateParam,
                              String openId,
                              String origin){
        int retCode = 0;
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", "融易兑");
        //SMS_206570115
        request.putQueryParameter("TemplateCode", templateCode);
        request.putQueryParameter("TemplateParam", templateParam);
        try {
            CommonResponse response = client.getCommonResponse(request);
            TSmsCode smsSendModel = new TSmsCode();
            smsSendModel.setId(SeqUtil.getSeqId());
            smsSendModel.setMobile(mobile);
            smsSendModel.setCode("");
            smsSendModel.setOpenId(openId);
            smsSendModel.setTemplateCode(templateCode);
            smsSendModel.setRespData(response.getData());
            smsSendModel.setOrigin(origin);
            smsCodeMapper.addSmsLog(smsSendModel);

        } catch (Exception e) {
            retCode = -1;
            e.printStackTrace();
            log.error("sendSmsCode:"+e.getMessage());
            sendAlarmService.sendAlarmMail(Constant.ALARM_MAIL,"【异常】平台-短信发送异常",e.getMessage());
        }
        return retCode;
    }
}
